{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 日夜图像分类器\n",
    "---\n",
    "\n",
    "日夜图像数据集由200个RGB彩色图像组成，分为两类：白天图像和夜晚图像。每个例子都有相同的数字：100个日图像和100个夜图像。\n",
    "\n",
    "我们希望建立一个分类器，可以把这些图像准确地标记为白天或黑夜。要完成这个任务，我们需要找出这两种图像之间的显著性特征！\n",
    "\n",
    "*注：所有图像都来自 [AMOS 数据集](http://cs.uky.edu/~jacobs/datasets/amos/) （众多户外场景档案）。*\n",
    "\n",
    "\n",
    "### 导入资源\n",
    "\n",
    "在开始使用项目代码之前，请导入你需要的库和资源。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2 # computer vision library\n",
    "import helpers\n",
    "\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.image as mpimg\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 训练并测试数据\n",
    "200张日/夜的图像被分成训练和测试数据集。\n",
    "\n",
    "* 这些图像中的60％是训练图像，供你在创建分类器时使用。\n",
    "* 另外40％是测试图像，将用于测试分类器的准确度。\n",
    "\n",
    "首先，我们设置一些变量来跟踪图像的存储位置：\n",
    "\n",
    "First, we set some variables to keep track of some where our images are stored:\n",
    "\n",
    "image_dir_training: the directory where our training image data is stored\n",
    "image_dir_test: the directory where our test image data is stored"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Image data directories\n",
    "image_dir_training = \"day_night_images/training/\"\n",
    "image_dir_test = \"day_night_images/test/\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 加载数据集\n",
    "\n",
    "前几行代码将加载训练日/夜图像，并将它们全部存储在变量`IMAGE_LIST`中。 该列表包含图像及其相关标签（“日”或“夜”）。\n",
    "\n",
    "例如， `IMAGE_LIST` 中的第一个图像标签对可以通过索引 ``` IMAGE_LIST[0][:]``` 访问。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Using the load_dataset function in helpers.py\n",
    "# Load training data\n",
    "IMAGE_LIST = helpers.load_dataset(image_dir_training)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构建输入图像和输出标签的 `STANDARDIZED_LIST` 函数\n",
    "\n",
    "该函数将输入一个图像标签对列表，并输出一个包含调整过的图像和数字标签的**标准**列表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Standardize all training images\n",
    "STANDARDIZED_LIST = helpers.standardize(IMAGE_LIST)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 将标准化数据可视化\n",
    "\n",
    "显示一个来自STANDARDIZED_LIST的标准化图片。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display a standardized image and its label\n",
    "\n",
    "# Select an image by index\n",
    "image_num = 0\n",
    "selected_image = STANDARDIZED_LIST[image_num][0]\n",
    "selected_label = STANDARDIZED_LIST[image_num][1]\n",
    "\n",
    "# Display image and data about it\n",
    "plt.imshow(selected_image)\n",
    "print(\"Shape: \"+str(selected_image.shape))\n",
    "print(\"Label [1 = day, 0 = night]: \" + str(selected_label))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 特征提取\n",
    "\n",
    "创建一个表示图像亮度的特征。我们将使用HSV颜色空间提取**平均亮度**。具体来说，我们将使用V通道（亮度测量），将V通道中的像素值相加，然后将该总和除以图像的面积，从而获得该图像的平均值。\n",
    "\n",
    "\n",
    "## 从 RGB 转换为 HSV\n",
    "\n",
    "在下方，一张测试图片被从 RGB 转换为 HSV 颜色空间，其中每个元素都用一张图片显示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert and image to HSV colorspace\n",
    "# Visualize the individual color channels\n",
    "\n",
    "image_num = 0\n",
    "test_im = STANDARDIZED_LIST[image_num][0]\n",
    "test_label = STANDARDIZED_LIST[image_num][1]\n",
    "\n",
    "# Convert to HSV\n",
    "hsv = cv2.cvtColor(test_im, cv2.COLOR_RGB2HSV)\n",
    "\n",
    "# Print image label\n",
    "print('Label: ' + str(test_label))\n",
    "\n",
    "# HSV channels\n",
    "h = hsv[:,:,0]\n",
    "s = hsv[:,:,1]\n",
    "v = hsv[:,:,2]\n",
    "\n",
    "# Plot the original image and the three channels\n",
    "f, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(20,10))\n",
    "ax1.set_title('Standardized image')\n",
    "ax1.imshow(test_im)\n",
    "ax2.set_title('H channel')\n",
    "ax2.imshow(h, cmap='gray')\n",
    "ax3.set_title('S channel')\n",
    "ax3.imshow(s, cmap='gray')\n",
    "ax4.set_title('V channel')\n",
    "ax4.imshow(v, cmap='gray')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "###  使用V通道查找平均亮度\n",
    "\n",
    "该函数会输入**标准化**的RGB图像并返回一个代表图像亮度平均水平的特征（单个值）。我们将使用此值将图像分类为白天或夜晚。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Find the average Value or brightness of an image\n",
    "def avg_brightness(rgb_image):\n",
    "    \n",
    "    # Convert image to HSV\n",
    "    hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)\n",
    "\n",
    "    # Add up all the pixel values in the V channel\n",
    "    sum_brightness = np.sum(hsv[:,:,2])\n",
    "    \n",
    "    ## TODO: Calculate the average brightness using the area of the image\n",
    "    # and the sum calculated above\n",
    "    avg = 0\n",
    "    \n",
    "    return avg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Testing average brightness levels\n",
    "# Look at a number of different day and night images and think about \n",
    "# what average brightness value separates the two types of images\n",
    "\n",
    "# As an example, a \"night\" image is loaded in and its avg brightness is displayed\n",
    "image_num = 190\n",
    "test_im = STANDARDIZED_LIST[image_num][0]\n",
    "\n",
    "avg = avg_brightness(test_im)\n",
    "print('Avg brightness: ' + str(avg))\n",
    "plt.imshow(test_im)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
